package controller

import (
	"YingShop/entity"
	querystruct "YingShop/queryStruct"
	"strconv"

	"github.com/gin-gonic/gin"
)

type ShopProductController struct {
	Result
}

func (shopController ShopProductController) Get(ctx *gin.Context) {
	productId, _ := strconv.Atoi(ctx.Param("productId"))
	product := entity.ShopProduct{ProductId: productId}
	err := product.Load()
	if err != nil {
		shopController.RetCode = -1
		shopController.Msg = err.Error()
	} else {
		shopController.RetCode = 0
		shopController.Msg = "success"
		shopController.Data = gin.H{
			"productInfo": product,
		}
	}
	ctx.JSON(200, shopController.Result)
}

func (productController ShopProductController) Post(ctx *gin.Context) {
	productAddParam := querystruct.ShopProductAddParam{}
	if err := ctx.ShouldBindJSON(&productAddParam); err != nil {
		productController.RetCode = -1
		productController.Msg = err.Error()
		ctx.JSON(200, productController.Result)
		return
	}
	productEntity := entity.ShopProduct{
		ProductName: productAddParam.ProductName,
		ProductDesc: productAddParam.ProductDesc,
		ProductNum:  productAddParam.ProductNum,
	}
	err := productEntity.Add()
	if err != nil {
		productController.RetCode = -1
		productController.Msg = err.Error()
		ctx.JSON(200, productController.Result)
		return
	}
	productController.RetCode = 0
	productController.Msg = "success"
	productController.Data = gin.H{
		"productId": productEntity.ProductId,
	}
	ctx.JSON(200, productController.Result)
}

func (productController ShopProductController) GetProductList(ctx *gin.Context) {
	categoryIdParam := ctx.Query("categoryId")
	categoryId := 0
	var err error
	if categoryIdParam != "" {
		categoryId, err = strconv.Atoi(categoryIdParam)
		if err != nil {
			productController.RetCode = -1
			productController.Msg = "分类参数不是数字"
			ctx.JSON(200, productController.Result)
			return
		}
	}
	pageSizeParam := ctx.Query("pageSize")
	pageSize := 10
	if pageSizeParam != "" {
		pageSize, err = strconv.Atoi(pageSizeParam)
		if err != nil {
			productController.RetCode = -1
			productController.Msg = "分页大小参数不是数字"
			ctx.JSON(200, productController.Result)
			return
		}
	}
	pageNumParam := ctx.Query("pageNum")
	pageNum := 1
	if pageNumParam != "" {
		pageNum, err = strconv.Atoi(pageSizeParam)
		if err != nil {
			productController.RetCode = -1
			productController.Msg = "页码参数不是数字"
			ctx.JSON(200, productController.Result)
			return
		}
	}
	productList := entity.ShopProductList{}
	err = productList.GetProductList(categoryId, pageNum, pageSize)
	if err != nil {
		productController.RetCode = -1
		productController.Msg = "获取商品列表时出现未知错误"
		ctx.JSON(200, productController.Result)
		return
	}
	productController.RetCode = 0
	productController.Msg = "success"
	productController.Data = gin.H{
		"productList": productList.ProductList,
		"totalNum":    productList.TotalNum,
	}
	ctx.JSON(200, productController.Result)
}
